﻿using Infragistics.Win.UltraMessageBox;
using Infragistics.Win.UltraWinGrid;
using OrBitDataModule.Dialog;
using OrBitDataModule;
using OrBitDataModule.Contract;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace OrBitDataModule.Controls
{
    public partial class ScriptManager : UserControl
    {
        //private TaskService Service = null;

        private CodeEditor codeEditor = null;
        public ScriptManager()
        {
            InitializeComponent();
            //Service = TaskService.Instance;
            InitScript();
        }


        /// <summary>
        /// 初始化脚本数据
        /// </summary>
        private void InitScript()
        {
            btn_addScript.Click += Btn_addScript_Click;
            btn_editScript.Click += Btn_editScript_Click;
            btn_removeScript.Click += Btn_removeScript_Click;
            btn_refreshScript.Click += Btn_refreshScript_Click;
            ultraGrid_Script.DoubleClickCell += UltraGrid_Script_DoubleClickCell;

            ultraTabControl_script.ActiveTabChanging += UltraTabControl_script_ActiveTabChanging;
            GetAllScript();
            InitEditor();
        }

        /// <summary>
        /// 初始化编辑器
        /// </summary>
        private void InitEditor()
        {
            codeEditor = new CodeEditor
            {
                Dock = DockStyle.Fill,
                ReadOnly = true
            };
            ultraTabPageControl_ScriptEdit.Controls.Add(codeEditor);
            codeEditor.OnSourceCodeSaved += CodeEditor_OnSourceCodeSaved;
        }

        private async void CodeEditor_OnSourceCodeSaved(object sender, string e)
        {
            UltraGridRow selectedRow = ultraGrid_Script.ActiveRow;
            if (selectedRow != null)
            {
                string dataProtocolScriptId = selectedRow.Cells["DataProtocolScriptId"].Value?.ToString();
                string scriptName = selectedRow.Cells["ScriptName"].Value?.ToString();
                string scriptCode = e;
                string scriptDescription = selectedRow.Cells["ScriptDescription"].Value?.ToString();
                var result = codeEditor.CompileScript();
                if (!result.Result)
                {
                    if (UltraMessageBoxManager.Show(this, $"脚本存在错误，确定要继续保存吗？\r\n{result.Message}", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information) != DialogResult.OK)
                    {
                        return;
                    }
                }
                var editResult = await ScriptApi.AddScript(dataProtocolScriptId, scriptName, scriptCode, scriptDescription);
                UltraMessageBoxManager.Show(this, editResult.Message, editResult.Result ? "提示" : "错误", MessageBoxButtons.OK, editResult.Result ? MessageBoxIcon.Information : MessageBoxIcon.Error);
            }
        }

        private void Btn_editScript_Click(object sender, EventArgs e)
        {
            if (ultraGrid_Script.ActiveRow == null)
            {
                UltraMessageBoxManager.Show(this, "未选中脚本项目！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            EditScript();
            ultraTabControl_script.SelectedTab = ultraTabControl_script.Tabs[1];
        }

        private void UltraTabControl_script_ActiveTabChanging(object sender, Infragistics.Win.UltraWinTabControl.ActiveTabChangingEventArgs e)
        {
            if (e.Tab.Index == 1)
            {
                if (ultraGrid_Script.ActiveRow == null)
                {
                    UltraMessageBoxManager.Show(this, "未选中脚本项目！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    e.Cancel = true;
                }
                EditScript();
            }
        }
        /// <summary>
        /// 修改脚本
        /// </summary>
        private async void EditScript()
        {
            UltraGridRow selectedRow = ultraGrid_Script.ActiveRow;
            if (selectedRow != null)
            {
                string scriptCode = selectedRow.Cells["ScriptCode"].Value?.ToString();
                string dataProtocolScriptId = selectedRow.Cells["DataProtocolScriptId"].Value?.ToString();
                if (string.IsNullOrWhiteSpace(scriptCode))
                {
                    scriptCode = Properties.Resource.DefaultScriptCode;
                }
                else
                {
                    var result = await ScriptApi.GetCodeAsync(dataProtocolScriptId);
                    scriptCode = result.ScriptCode;
                }
                codeEditor.LoadSource(scriptCode);
                codeEditor.ReadOnly = false;
            }
        }

        private void UltraGrid_Script_DoubleClickCell(object sender, DoubleClickCellEventArgs e)
        {
            string dataProtocolScriptId = e.Cell.Row.GetCellValue("DataProtocolScriptId").ToString();
            string scriptName = e.Cell.Row.GetCellValue("ScriptName").ToString();
            string scriptCode = e.Cell.Row.GetCellValue("ScriptCode").ToString();
            string scriptDescription = e.Cell.Row.GetCellValue("ScriptDescription").ToString();
            using (AddScript addScript = new AddScript(true, dataProtocolScriptId, scriptName, scriptCode, scriptDescription))
            {
                addScript.ShowDialog();
                GetAllScript();
            }
        }

        private async void GetAllScript()
        {
            var result = await ScriptApi.GetAllScript();
            this.ultraGrid_Script.DataSource = result.Script.Data;
            ultraGrid_Script.DataBind();
        }

        private void Btn_addScript_Click(object sender, EventArgs e)
        {
            using (AddScript addScript = new AddScript(false, string.Empty, string.Empty, string.Empty, string.Empty))
            {
                addScript.ShowDialog();
                GetAllScript();
            }
        }

        private async void Btn_removeScript_Click(object sender, EventArgs e)
        {
            UltraGridRow selectedRow = ultraGrid_Script.ActiveRow;
            if (selectedRow != null)
            {
                string dataProtocolScriptId = selectedRow.Cells["DataProtocolScriptId"].Value?.ToString();
                if (UltraMessageBoxManager.Show(this, "确定要删除选中项？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information) == DialogResult.OK)
                {
                    var result = await ScriptApi.RemoveScript(dataProtocolScriptId);
                    UltraMessageBoxManager.Show(this, result.Message, result.Result ? "提示" : "错误", MessageBoxButtons.OK, result.Result ? MessageBoxIcon.Information : MessageBoxIcon.Error);
                    GetAllScript();
                }
            }
        }

        private void Btn_refreshScript_Click(object sender, EventArgs e)
        {
            GetAllScript();
        }


    }
}
